package chat;
        
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;

public class ChatRoomClient extends JFrame implements Runnable{
    
    private static int count=0;
    
    JPanel panel1,panel2;
    JButton button1,button2;
    JTextField textField1,textField2;
    JLabel label1;
    TextArea textArea;
    ScrollPane sPanel;
    JMenuBar Jmb;
    JMenu m ;
    JMenuItem mi1,mi2;
    JComboBox cmbExp;
    
 //net
 PrintWriter out;
 BufferedReader in=null;
 Socket sock;
 public final static int DEFAULT_PORT= 23000; 
 Thread readThread;
 boolean isTrue=true;//thread can go on runing 
 
 public ChatRoomClient(){
  try{
   jbInit();
  }catch(Exception e){
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args){//main method
  ChatRoomClient c=new ChatRoomClient();
  c.show();
 }
 
 private void jbInit(){//should set size,position and Font of every component
  
  button1=new JButton("Connect to Server (Default) :　");// set Font
  button2=new JButton("Send");
  button2.setEnabled(false);
  textField1=new JTextField("10.20.85.2");
  textField2=new JTextField("+++++++++++++++++++++++++++++");
  textField2.setEditable(false);
  textField2.setSize(10,30);
  label1=new JLabel("Msg:");
  panel1=new JPanel();
  panel2=new JPanel();
  sPanel=new ScrollPane();
  textArea=new TextArea();
  textArea.setBackground(Color.white);
  textArea.setForeground(Color.DARK_GRAY);
  textArea.setEditable(false);
  
//  Image image ;
//  image= this.getToolkit().getImage("C:\\Documents and Settings\\Administrator\\Desktop\\Chat\\src\\Picture1.jpg");

  cmbExp = new JComboBox();
  cmbExp .addItem("Smiling");
  cmbExp .addItem("angrily");
  cmbExp .addItem("Cautiously");


  cmbExp .setSelectedIndex(0);
//  cmbExp.setEnabled(false);

 
  //panel1  
  //press [button1: Connect ]to connect the client to server
  button1.addActionListener(new java.awt.event.ActionListener(){
   public void actionPerformed(ActionEvent e){
    button1_actionPerformed(e);
   }
  });
  //textField1:for input the address of server;be registered to KeyListener.
  //press key:Enter to connect the client to server
  textField1.addKeyListener(new textField1_KeyAdapter(this));//java.awt.event.KeyAdapter()
  panel1.add(button1);
  panel1.add(textField1);
  
  //sPanel  ScrollPane
  sPanel.add(textArea);
  
  //panel2
  //press [button2: Send] to send message
  button2.addActionListener(new java.awt.event.ActionListener(){
   public void actionPerformed(ActionEvent e){
    button2_actionPerformed(e);
   }
  });
  //textField2:for input message;be registered to KeyListener.
  //press key:Enter to send message
  textField2.addKeyListener(new textField2_KeyAdapter(this));
  panel2.add(cmbExp);
  panel2.add(label1);
  panel2.add(textField2);
  panel2.add(button2);
  
  //frame
  this.addWindowListener(new ChatFrame_WindowAdapter(this));//frame is registered to WindowListener
  this.setLayout(new BorderLayout());
  this.setSize(500,400);
  this.add(panel1,BorderLayout.NORTH);
  this.add(sPanel,BorderLayout.CENTER);
  this.add(panel2,BorderLayout.SOUTH);
   
    
 }
 public boolean CheckName(String name){
    boolean IsOK = true;
     if(name.length() >=20)
     {
       IsOK =false;
     }
     if(name.contains("\\")){
        IsOK = false;
    }
    if(name.isEmpty())
    {
        IsOK = false;
    }
    if(name.contains("\0"))
    {
        IsOK = false;
    }
     return IsOK;
 }
 public void startConnect(){//开始连接
  try{
      sock=new Socket(textField1.getText(),DEFAULT_PORT);
      if(sock!=null){//connection successed
          PrintMsg("Connect successfully!");
          this.textField1.setEditable(false);
          this.button1.setEnabled(false);
          this.button2.setEnabled(true);
          this.textField2.setText("Now Enter your nickname");
         
          this.textField2.setEditable(true);
          this.textField2.selectAll();
      }
      in=new BufferedReader(new InputStreamReader(sock.getInputStream()));
      out=new PrintWriter(sock.getOutputStream());
  }catch(IOException ex){
      System.out.println(ex.getMessage());
      PrintMsg("Connect failed!");
  }
  readThread=new Thread(this);
  readThread.start(); 
 }
 
 public void sendInformation(){  
     
     String empression = "[**  "+ this.cmbExp.getSelectedItem().toString()+" **] ";
     if(count <= 1)
     {         
         if(this.CheckName(textField2.getText())){ 
             out.println(textField2.getText());              
          }
         else{
             count --;
             textField2.setText("Sorry,Name is Invalid!");
             textArea.append("Name should be less than 20.\n and  not contains special character,such as :SPACE \n ");
             textField2.setFocusable(true);
         }
          
     }
     else  
     {
         out.println(empression+textField2.getText());
     }
       
     textField2.selectAll();
     out.flush();
 }
 
 private void button1_actionPerformed(ActionEvent e){//连接按钮
    startConnect();
 }
   
 private void button2_actionPerformed(ActionEvent e){//发送按钮
     count++;
     sendInformation();
 }
   
 public void stopRun(){//to stop the running thread
  isTrue=false;
 } 
 
 //  
 public void PrintMsg(String msg){
  textArea.append(msg);
  textArea.append("\n\n");
 }
 
 public void run(){
  String msg;
  isTrue=true;
  while(isTrue){
   try{
    msg=in.readLine();
    if(msg == null){
        PrintMsg("++++++++Sorry,Server exit+++++++++");
        stopRun();
    }
     else
        PrintMsg(msg);
    Thread.sleep(1000);    
   }catch(IOException e){
   PrintMsg(e.toString());
   }catch(InterruptedException ei){
   PrintMsg(ei.toString());
   }
  }
  //endConnect();
  try{
 //服务器退出关闭连接和相关的"流"
   sock.close();
   in.close();
   out.close();
  }catch(IOException ioe){} 
 }
 
 //Close the Form ! If the socket-connection and revelent "streams" remain exist,then terminate them
 public void exit(){
  try{
      //send "Client exit!" to Server!
      out.println("Client exit!");
      out.flush();
  }catch(Exception exc){}
  //endConnect();
  try{//close IOstream 
      sock.close();
      in.close();
      out.close();
  }catch(IOException ioe){}
  finally{    
      System.exit(0);
  }
 }
}



//+++++++++++++++++++++++++++++++事件处理函数++++++++++++++++++++++++++++++++++++++++++++++++
//textField1的键击事件适配器
class textField1_KeyAdapter extends java.awt.event.KeyAdapter{
 ChatRoomClient chatFrame;
 
 public textField1_KeyAdapter(ChatRoomClient chatFrame){
  this.chatFrame=chatFrame;
 }
 
 @Override
 public void keyPressed(KeyEvent e){//If pressed "Enter"，then start to connect !
  int j=e.getKeyCode();
  if(j==e.VK_ENTER){
   chatFrame.startConnect();
  }
 }
}

//textField2的键击事件适配器
class textField2_KeyAdapter extends java.awt.event.KeyAdapter{
 ChatRoomClient chatFrame;
 
 public textField2_KeyAdapter(ChatRoomClient chatFrame){
  this.chatFrame=chatFrame;
 }
 
 @Override
 public void keyPressed(KeyEvent e){//If pressed "Enter"，then start to send message!

     int j=e.getKeyCode();
     if(j==e.VK_ENTER){
         chatFrame.sendInformation();
     }
 }
}

//窗口关闭事件适配器
 class ChatFrame_WindowAdapter extends java.awt.event.WindowAdapter{
     ChatRoomClient chatFrame;
     public ChatFrame_WindowAdapter(ChatRoomClient chatFrame){
         this.chatFrame=chatFrame;
     }
     @Override
     public void windowClosing(WindowEvent e){//exit program
         chatFrame.exit();//reference to the method exit() in ChatRoomClient.
     }
}

 
 
 

